package com.gjy.redis;

import com.gjy.comment.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBitSet;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-02-14 14:30:49
 */
@Slf4j
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Resource
    private RedissonClient redissonClient;

    @PostMapping("/count")
    public AjaxResult countSize() {
        RBitSet bitSet = redissonClient.getBitSet(RedisConstant.COUNT_SIZE);
        long count = bitSet.size();
        bitSet.set(count + 1, true);
        return AjaxResult.ok();
    }

    @PostMapping("/lock/{expire}")
    public AjaxResult lock(@PathVariable Integer expire) {
        RLock rLock = redissonClient.getLock("lock_1");
        try {
            boolean b = rLock.tryLock(expire, TimeUnit.SECONDS);
            if (b) {
                log.info(Thread.currentThread().getName() + " 获取到锁");
            } else {
                log.info(Thread.currentThread().getName() + " 获取到锁失败 -----");
            }
        } catch (InterruptedException e) {
            rLock.unlock();
            throw new RuntimeException(e);
        }
        return AjaxResult.ok();
    }
}
